<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>SpringSecurity学习笔记 | Jixer的小屋</title><meta name="author" content="Jixer"><meta name="copyright" content="Jixer"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="两个核心功能：认证和授权 基本原理SpringSecurity本质是一个过滤器链 1org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil ter org.springframework.security.web.context.SecurityContextPersistenceFi">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringSecurity学习笔记">
<meta property="og:url" content="http://www.lijunxi.site/posts/1714087543/index.html">
<meta property="og:site_name" content="Jixer的小屋">
<meta property="og:description" content="两个核心功能：认证和授权 基本原理SpringSecurity本质是一个过滤器链 1org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil ter org.springframework.security.web.context.SecurityContextPersistenceFi">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://q1.qlogo.cn/g?b=qq&nk=2770063826&s=640">
<meta property="article:published_time" content="2024-01-16T15:39:49.000Z">
<meta property="article:modified_time" content="2024-05-07T03:10:23.278Z">
<meta property="article:author" content="Jixer">
<meta property="article:tag" content="SpringSecurity">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://q1.qlogo.cn/g?b=qq&nk=2770063826&s=640"><link rel="shortcut icon" href="/img/logo/favicon.ico"><link rel="canonical" href="http://www.lijunxi.site/posts/1714087543/index.html"><link rel="preconnect"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css?v=4.13.0"><link rel="stylesheet" href="/pluginsSrc/@fortawesome/fontawesome-free/css/all.min.css?v=6.5.1"><link rel="stylesheet" href="/pluginsSrc/@fancyapps/ui/dist/fancybox/fancybox.css?v=5.0.33" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: '/pluginsSrc/@egjs/infinitegrid/dist/infinitegrid.min.js?v=4.11.1',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'SpringSecurity学习笔记',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-05-07 11:10:23'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="/css/custom-all-min.css"><link rel="stylesheet" href="/css/custom-fancybox-min.css"><link rel="stylesheet" href="/css/custom-share-min.css"><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="" data-original="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">19</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="Jixer的小屋"><span class="site-name">Jixer的小屋</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/links/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">SpringSecurity学习笔记</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-16T15:39:49.000Z" title="发表于 2024-01-16 23:39:49">2024-01-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-05-07T03:10:23.278Z" title="更新于 2024-05-07 11:10:23">2024-05-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>16分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="SpringSecurity学习笔记"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>两个核心功能：<strong>认证</strong>和<strong>授权</strong></p>
<h2 id="基本原理"><a href="#基本原理" class="headerlink" title="基本原理"></a>基本原理</h2><p>SpringSecurity本质是一个过滤器链</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil ter org.springframework.security.web.context.SecurityContextPersistenceFilter  org.springframework.security.web.header.HeaderWriterFilter org.springframework.security.web.csrf.CsrfFilter org.springframework.security.web.authentication.logout.LogoutFilter  org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter  org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter  org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter org.springframework.security.web.savedrequest.RequestCacheAwareFilter org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter org.springframework.security.web.authentication.AnonymousAuthenticationFilter  org.springframework.security.web.session.SessionManagementFilter  org.springframework.security.web.access.ExceptionTranslationFilter  org.springframework.security.web.access.intercept.FilterSecurityIntercepto</span><br></pre></td></tr></table></figure>

<p>重点三个：</p>
<p><code>FilterSecurityInterceptor</code>：是一个方法级的权限过滤器, 基本位于过滤链的最底部。</p>
<p><code>ExceptionTranslationFilter</code>：是个异常过滤器，用来处理在认证授权过程中抛出的异常</p>
<p><code>UsernamePasswordAuthenticationFilter</code> ：对&#x2F;login 的 POST 请求做拦截，校验表单中用户 名，密码</p>
<h2 id="过滤器加载流程"><a href="#过滤器加载流程" class="headerlink" title="过滤器加载流程"></a>过滤器加载流程</h2><h3 id="DelegatingFilterProxy类"><a href="#DelegatingFilterProxy类" class="headerlink" title="DelegatingFilterProxy类"></a>DelegatingFilterProxy类</h3><p>首先执行<code>doFilter</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain filterChain)</span> <span class="keyword">throws</span> ServletException, IOException &#123;</span><br><span class="line">        <span class="type">Filter</span> <span class="variable">delegateToUse</span> <span class="operator">=</span> <span class="built_in">this</span>.delegate;</span><br><span class="line">        <span class="keyword">if</span> (delegateToUse == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span>(<span class="built_in">this</span>.delegateMonitor) &#123;</span><br><span class="line">                delegateToUse = <span class="built_in">this</span>.delegate;</span><br><span class="line">                <span class="keyword">if</span> (delegateToUse == <span class="literal">null</span>) &#123;</span><br><span class="line">                    <span class="type">WebApplicationContext</span> <span class="variable">wac</span> <span class="operator">=</span> <span class="built_in">this</span>.findWebApplicationContext();</span><br><span class="line">                    <span class="keyword">if</span> (wac == <span class="literal">null</span>) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalStateException</span>(<span class="string">&quot;No WebApplicationContext found: no ContextLoaderListener or DispatcherServlet registered?&quot;</span>);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    delegateToUse = <span class="built_in">this</span>.initDelegate(wac);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="built_in">this</span>.delegate = delegateToUse;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<p>接着执行<code>initDelegate</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> Filter <span class="title function_">initDelegate</span><span class="params">(WebApplicationContext wac)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line">       <span class="type">String</span> <span class="variable">targetBeanName</span> <span class="operator">=</span> <span class="built_in">this</span>.getTargetBeanName();</span><br><span class="line">       Assert.state(targetBeanName != <span class="literal">null</span>, <span class="string">&quot;No target bean name set&quot;</span>);</span><br><span class="line">       <span class="type">Filter</span> <span class="variable">delegate</span> <span class="operator">=</span> (Filter)wac.getBean(targetBeanName, Filter.class);</span><br><span class="line">       <span class="keyword">if</span> (<span class="built_in">this</span>.isTargetFilterLifecycle()) &#123;</span><br><span class="line">           delegate.init(<span class="built_in">this</span>.getFilterConfig());</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">return</span> delegate;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p><code>targetBeanName</code>在<code>SpringSecurity</code>中有一个固定的名字：<code>FilterChainProxy</code></p>
<h3 id="FilterChainProxy类"><a href="#FilterChainProxy类" class="headerlink" title="FilterChainProxy类"></a>FilterChainProxy类</h3><p>首先执行<code>doFilter</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">    <span class="type">boolean</span> <span class="variable">clearContext</span> <span class="operator">=</span> request.getAttribute(FILTER_APPLIED) == <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">if</span> (clearContext) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            request.setAttribute(FILTER_APPLIED, Boolean.TRUE);</span><br><span class="line">            <span class="built_in">this</span>.doFilterInternal(request, response, chain);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            SecurityContextHolder.clearContext();</span><br><span class="line">            request.removeAttribute(FILTER_APPLIED);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.doFilterInternal(request, response, chain);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行<code>doFilterInternal</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">doFilterInternal</span><span class="params">(ServletRequest request, ServletResponse response, FilterChain chain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">        <span class="type">FirewalledRequest</span> <span class="variable">fwRequest</span> <span class="operator">=</span> <span class="built_in">this</span>.firewall.getFirewalledRequest((HttpServletRequest)request);</span><br><span class="line">        <span class="type">HttpServletResponse</span> <span class="variable">fwResponse</span> <span class="operator">=</span> <span class="built_in">this</span>.firewall.getFirewalledResponse((HttpServletResponse)response);</span><br><span class="line">        List&lt;Filter&gt; filters = <span class="built_in">this</span>.getFilters((HttpServletRequest)fwRequest);</span><br><span class="line">        <span class="keyword">if</span> (filters != <span class="literal">null</span> &amp;&amp; filters.size() != <span class="number">0</span>) &#123;</span><br><span class="line">            FilterChainProxy.<span class="type">VirtualFilterChain</span> <span class="variable">vfc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FilterChainProxy</span>.VirtualFilterChain(fwRequest, chain, filters);</span><br><span class="line">            vfc.doFilter(fwRequest, fwResponse);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(UrlUtils.buildRequestUrl(fwRequest) + (filters == <span class="literal">null</span> ? <span class="string">&quot; has no matching filters&quot;</span> : <span class="string">&quot; has an empty filter list&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            fwRequest.reset();</span><br><span class="line">            chain.doFilter(fwRequest, fwResponse);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p><code>  List&lt;Filter&gt; filters = this.getFilters((HttpServletRequest)fwRequest);</code>会执行<code>getFilters</code>方法，它会把过滤器一个一个加载到过滤链中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> List&lt;Filter&gt; <span class="title function_">getFilters</span><span class="params">(HttpServletRequest request)</span> &#123;</span><br><span class="line">      <span class="type">Iterator</span> <span class="variable">var2</span> <span class="operator">=</span> <span class="built_in">this</span>.filterChains.iterator();</span><br><span class="line"></span><br><span class="line">      SecurityFilterChain chain;</span><br><span class="line">      <span class="keyword">do</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (!var2.hasNext()) &#123;</span><br><span class="line">              <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">          &#125;</span><br><span class="line"></span><br><span class="line">          chain = (SecurityFilterChain)var2.next();</span><br><span class="line">      &#125; <span class="keyword">while</span>(!chain.matches(request));</span><br><span class="line"></span><br><span class="line">      <span class="keyword">return</span> chain.getFilters();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="重要接口"><a href="#重要接口" class="headerlink" title="重要接口"></a>重要接口</h2><h3 id="UserDetailsService"><a href="#UserDetailsService" class="headerlink" title="UserDetailsService"></a>UserDetailsService</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line">    UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String var1)</span> <span class="keyword">throws</span> UsernameNotFoundException;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>当什么也没有配置的时候，账号和密码是由 Spring Security 定义生成的。而在实际项目中 账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。如果需要自定义逻辑时，只需要实现 <code>UserDetailsService </code>接口即可。</p>
</blockquote>
<p>作用：查询数据库用户名和密码过程</p>
<ul>
<li>创建类继承<code>UsernamePasswordAuthenticationFilter</code>，重写三个方法</li>
<li>创建类实现<code>UserDetailService</code>，返回<code>UserDetails</code>对象（框架提供的对象）</li>
</ul>
<p><code>UserDetails</code>类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">UserDetails</span> <span class="keyword">extends</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line">  	<span class="comment">// 表示获取登录用户所有权限</span></span><br><span class="line">    Collection&lt;? <span class="keyword">extends</span> <span class="title class_">GrantedAuthority</span>&gt; getAuthorities();</span><br><span class="line">    <span class="comment">// 表示获取密码</span></span><br><span class="line">    String <span class="title function_">getPassword</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 表示获取用户名</span></span><br><span class="line">    String <span class="title function_">getUsername</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 表示判断账户是否过期</span></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">isAccountNonExpired</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 表示判断账户是否被锁定</span></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">isAccountNonLocked</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 表示凭证&#123;密码&#125;是否过期</span></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">isCredentialsNonExpired</span><span class="params">()</span>;</span><br><span class="line">    <span class="comment">// 表示当前用户是否可用</span></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">isEnabled</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="PasswordEncoder"><a href="#PasswordEncoder" class="headerlink" title="PasswordEncoder"></a>PasswordEncoder</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">PasswordEncoder</span> &#123;</span><br><span class="line">    <span class="comment">// 表示把参数按照特定的解析规则进行解析</span></span><br><span class="line">    String <span class="title function_">encode</span><span class="params">(CharSequence var1)</span>;</span><br><span class="line">	<span class="comment">// 表示验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹配，则返回 true；如果不匹配，则返回 false。第一个参数表示需要被解析的密码。第二个参数表示存储的密码。</span></span><br><span class="line">    <span class="type">boolean</span> <span class="title function_">matches</span><span class="params">(CharSequence var1, String var2)</span>;</span><br><span class="line">	<span class="comment">// 表示如果解析的密码能够再次进行解析且达到更安全的结果则返回 true，否则返回false。默认返回 false。</span></span><br><span class="line">    <span class="keyword">default</span> <span class="type">boolean</span> <span class="title function_">upgradeEncoding</span><span class="params">(String encodedPassword)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接口实现</p>
<p><code>BCryptPasswordEncoder</code> 是 Spring Security 官方推荐的密码解析器，是对<code>PasswordEncoder</code>类的实现</p>
<p>加密</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> String <span class="title function_">encode</span><span class="params">(CharSequence rawPassword)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (rawPassword == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalArgumentException</span>(<span class="string">&quot;rawPassword cannot be null&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            String salt;</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">this</span>.random != <span class="literal">null</span>) &#123;</span><br><span class="line">                salt = BCrypt.gensalt(<span class="built_in">this</span>.version.getVersion(), <span class="built_in">this</span>.strength, <span class="built_in">this</span>.random);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                salt = BCrypt.gensalt(<span class="built_in">this</span>.version.getVersion(), <span class="built_in">this</span>.strength);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> BCrypt.hashpw(rawPassword.toString(), salt);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>匹配</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">matches</span><span class="params">(CharSequence rawPassword, String encodedPassword)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (rawPassword == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalArgumentException</span>(<span class="string">&quot;rawPassword cannot be null&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (encodedPassword != <span class="literal">null</span> &amp;&amp; encodedPassword.length() != <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!<span class="built_in">this</span>.BCRYPT_PATTERN.matcher(encodedPassword).matches()) &#123;</span><br><span class="line">                <span class="built_in">this</span>.logger.warn(<span class="string">&quot;Encoded password does not look like BCrypt&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> BCrypt.checkpw(rawPassword.toString(), encodedPassword);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.logger.warn(<span class="string">&quot;Empty encoded password&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="SpringSecurity-Web-权限方案"><a href="#SpringSecurity-Web-权限方案" class="headerlink" title="SpringSecurity Web 权限方案"></a>SpringSecurity Web 权限方案</h2><p>授权和认证两种</p>
<h3 id="设置用户名和密码"><a href="#设置用户名和密码" class="headerlink" title="设置用户名和密码"></a>设置用户名和密码</h3><p>方式一：配置文件实现</p>
<figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring.security.user.name</span>=<span class="string">ljx</span></span><br><span class="line"><span class="attr">spring.security.user.password</span>=<span class="string">ljx</span></span><br></pre></td></tr></table></figure>

<p>方式二：配置类实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="type">BCryptPasswordEncoder</span> <span class="variable">cryptPasswordEncoder</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">        auth.inMemoryAuthentication().withUser(<span class="string">&quot;ljx&quot;</span>).password(cryptPasswordEncoder.encode(<span class="string">&quot;ljx&quot;</span>)).roles(<span class="string">&quot;user&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方式三：自定义实现类</p>
<p>创建配置类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SecurityConfig</span> <span class="keyword">extends</span> <span class="title class_">WebSecurityConfigurerAdapter</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 自定义类实现登录</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> auth</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailsService userDetailsService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(AuthenticationManagerBuilder auth)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> PasswordEncoder <span class="title function_">passwordEncoder</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>编写<code>userDetailService</code>实现类，返回<code>User</code>对象&#96;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service(&quot;userDetailsService&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyUserDetailsService</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String s)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        List&lt;GrantedAuthority&gt; list = AuthorityUtils.commaSeparatedStringToAuthorityList(<span class="string">&quot;role&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;ljx&quot;</span>, <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>().encode(<span class="string">&quot;ljx&quot;</span>), list);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="整合数据库实现登录"><a href="#整合数据库实现登录" class="headerlink" title="整合数据库实现登录"></a>整合数据库实现登录</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service(&quot;userDetailsService&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyUserDetailsService</span> <span class="keyword">implements</span> <span class="title class_">UserDetailsService</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> UserDetails <span class="title function_">loadUserByUsername</span><span class="params">(String s)</span> <span class="keyword">throws</span> UsernameNotFoundException &#123;</span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span> userMapper.queryUserByUsername(s);</span><br><span class="line">        <span class="keyword">if</span>(s == <span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">UsernameNotFoundException</span>(<span class="string">&quot;用户不存在&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        List&lt;GrantedAuthority&gt; list = AuthorityUtils.commaSeparatedStringToAuthorityList(<span class="string">&quot;role&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">User</span>(user.getUsername(), <span class="keyword">new</span> <span class="title class_">BCryptPasswordEncoder</span>().encode(user.getPassword()), list);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="路径拦截路径拦截"><a href="#路径拦截路径拦截" class="headerlink" title="路径拦截路径拦截"></a>路径拦截路径拦截</h3><p>实现<code>configure</code>的另一个方法（与上面的不一样）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">           http.and()</span><br><span class="line">                .authorizeRequests()</span><br><span class="line">                .antMatchers(<span class="string">&quot;/api/main/t&quot;</span>).permitAll() <span class="comment">// 不需要认证</span></span><br><span class="line">                .anyRequest().authenticated()</span><br><span class="line">                .and().csrf().disable();  <span class="comment">// 关闭csrf</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="角色权限访问控制"><a href="#角色权限访问控制" class="headerlink" title="角色权限访问控制"></a>角色权限访问控制</h2><h3 id="hasAuthority"><a href="#hasAuthority" class="headerlink" title="hasAuthority"></a>hasAuthority</h3><p>如果当前的主体具有指定的权限，则返回 true,否则返回 false</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.antMatchers(<span class="string">&quot;/test1&quot;</span>).hasAuthority(<span class="string">&quot;admin&quot;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="hasAnyAuthority"><a href="#hasAnyAuthority" class="headerlink" title="hasAnyAuthority"></a>hasAnyAuthority</h3><p>如果当前的主体有任何提供的角色（给定的作为一个逗号分隔的字符串表）的话，返回 true</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.antMatchers(<span class="string">&quot;/test2&quot;</span>).hasAnyAuthority(<span class="string">&quot;admin, role&quot;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="hasRole"><a href="#hasRole" class="headerlink" title="hasRole"></a>hasRole</h3><p>如果用户具备给定角色就允许访问,否则出现 403。 如果当前主体具有指定的角色，则返回 true。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.antMatchers(<span class="string">&quot;/test3&quot;</span>).hasRole(<span class="string">&quot;sale&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>这个方法于之前两个不同的是底层原码是默认加了<code>ROLE_</code>前缀，所以在添加用户权限的时候需注意在角色前面加<code>ROLE_</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> String <span class="title function_">hasRole</span><span class="params">(String role)</span> &#123;</span><br><span class="line">        Assert.notNull(role, <span class="string">&quot;role cannot be null&quot;</span>);</span><br><span class="line">        <span class="keyword">if</span> (role.startsWith(<span class="string">&quot;ROLE_&quot;</span>)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">IllegalArgumentException</span>(<span class="string">&quot;role should not start with &#x27;ROLE_&#x27; since it is automatically inserted. Got &#x27;&quot;</span> + role + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;hasRole(&#x27;ROLE_&quot;</span> + role + <span class="string">&quot;&#x27;)&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="hasAnyRole"><a href="#hasAnyRole" class="headerlink" title="hasAnyRole"></a>hasAnyRole</h3><p>表示用户具备任何一个条件都可以访问</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">.antMatchers(<span class="string">&quot;/test3&quot;</span>).hasAnyRole(<span class="string">&quot;sale&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>要求于<code>hasRole</code>一样</p>
<h3 id="自定义403页面"><a href="#自定义403页面" class="headerlink" title="自定义403页面"></a>自定义403页面</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http.exceptionHandling().accessDeniedPage(<span class="string">&quot;/unauth&quot;</span>);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/unauth&quot;)</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">t4</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;unauth&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="注解使用"><a href="#注解使用" class="headerlink" title="注解使用"></a>注解使用</h3><h4 id="Secured"><a href="#Secured" class="headerlink" title="@Secured"></a>@Secured</h4><p><strong>使用注解先要开启注解功能</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableGlobalMethodSecurity(securedEnabled = true)</span></span><br></pre></td></tr></table></figure>

<p>判断是否具有角色，另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“</p>
<p>在方法上加上这个注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Secured(&#123;&quot;ROLE_sole&quot;, &quot;ROLE_aaa&quot;&#125;)</span></span><br></pre></td></tr></table></figure>

<h4 id="PreAuthorize"><a href="#PreAuthorize" class="headerlink" title="@PreAuthorize"></a>@PreAuthorize</h4><p><strong>使用注解先要开启注解功能</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableGlobalMethodSecurity(prePostEnabled = true)</span></span><br></pre></td></tr></table></figure>

<p>注解适合进入方法前的权限验证</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PreAuthorize(&quot;hasAnyAuthority(&#x27;menu:system&#x27;)&quot;)</span></span><br><span class="line"><span class="comment">// 此处hasAnyAuthority可以换成hasAnyRole，hasRole，hasAnyAuthority其中一个</span></span><br></pre></td></tr></table></figure>

<h4 id="PostAuthorize"><a href="#PostAuthorize" class="headerlink" title="@PostAuthorize"></a>@PostAuthorize</h4><p><strong>使用注解先要开启注解功能</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@EnableGlobalMethodSecurity(prePostEnabled = true</span></span><br></pre></td></tr></table></figure>

<p>在方法执行后再进行权限验证（接口里面方法任会被执行，只是最后会权限验证），适合验证带有返回值的权限</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@PostAuthorize(&quot;hasAnyAuthority(&#x27;menu:system&#x27;)&quot;)</span></span><br></pre></td></tr></table></figure>

<h4 id="PostFilter"><a href="#PostFilter" class="headerlink" title="@PostFilter"></a>@PostFilter</h4><p>权限验证之后对数据进行过滤 留下用户名是<code> admin1</code>的数据，表达式中的 <code>filterObject</code>引用的是方法返回值 List 中的某一个元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;getAll&quot;)</span></span><br><span class="line"><span class="meta">@PreAuthorize(&quot;hasRole(&#x27;ROLE_role&#x27;)&quot;)</span></span><br><span class="line"><span class="meta">@PostFilter(&quot;filterObject.username == &#x27;admin1&#x27;&quot;)</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> List&lt;UserInfo&gt; <span class="title function_">getAllUser</span><span class="params">()</span>&#123;</span><br><span class="line"> ArrayList&lt;UserInfo&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line"> list.add(<span class="keyword">new</span> <span class="title class_">UserInfo</span>(<span class="number">1l</span>,<span class="string">&quot;admin1&quot;</span>,<span class="string">&quot;6666&quot;</span>));</span><br><span class="line"> list.add(<span class="keyword">new</span> <span class="title class_">UserInfo</span>(<span class="number">2l</span>,<span class="string">&quot;admin2&quot;</span>,<span class="string">&quot;888&quot;</span>));</span><br><span class="line"><span class="keyword">return</span> list;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最终返回页面的数据</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">[</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;id&quot;</span><span class="punctuation">:</span> <span class="number">1</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;username&quot;</span><span class="punctuation">:</span> <span class="string">&quot;admin1&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="attr">&quot;num&quot;</span><span class="punctuation">:</span> <span class="string">&quot;6666&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span></span><br><span class="line"><span class="punctuation">]</span></span><br></pre></td></tr></table></figure>

<h4 id="PreFilter"><a href="#PreFilter" class="headerlink" title="@PreFilter"></a>@PreFilter</h4><p>进入控制器之前对数据进行过滤</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;getTestPreFilter&quot;)</span></span><br><span class="line"><span class="meta">@PreAuthorize(&quot;hasRole(&#x27;ROLE_role&#x27;)&quot;)</span></span><br><span class="line"><span class="meta">@PreFilter(value = &quot;filterObject.id % 2 == 0&quot;)</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> List&lt;UserInfo&gt; <span class="title function_">getTestPreFilter</span><span class="params">(<span class="meta">@RequestBody</span> List&lt;UserInfo&gt; </span></span><br><span class="line"><span class="params">list)</span>&#123;</span><br><span class="line"> list.forEach(t-&gt; &#123;</span><br><span class="line"> System.out.println(t.getId()+<span class="string">&quot;\t&quot;</span>+t.getUsername());</span><br><span class="line"> &#125;);</span><br><span class="line"><span class="keyword">return</span> list;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最终接收到的参数只有id为偶数才能被接收</p>
<h3 id="退出登录"><a href="#退出登录" class="headerlink" title="退出登录"></a>退出登录</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http.logout().logoutUrl(<span class="string">&quot;/logout&quot;</span>).logoutSuccessUrl(<span class="string">&quot;/index&quot;</span>).permitAll</span><br></pre></td></tr></table></figure>

<h2 id="CSRF"><a href="#CSRF" class="headerlink" title="CSRF"></a>CSRF</h2><p>跨站请求伪造（英语：Cross-site request forgery），也被称为 one-click  attack 或者 session riding，通常缩写为 CSRF 或者 XSRF， 是一种挟制用户在当前已 登录的 Web 应用程序上执行非本意的操作的攻击方法。跟跨网站脚本（XSS）相比，XSS 利用的是用户对指定网站的信任，CSRF 利用的是网站对用户网页浏览器的信任</p>
<p>跨站请求攻击，简单地说，是攻击者通过一些技术手段欺骗用户的浏览器去访问一个 自己曾经认证过的网站并运行一些操作（如发邮件，发消息，甚至财产操作如转账和购买 商品）。由于浏览器曾经认证过，所以被访问的网站会认为是真正的用户操作而去运行。 这利用了 web 中用户身份验证的一个漏洞：简单的身份验证只能保证请求发自某个用户的 浏览器，却不能保证请求本身是用户自愿发出的。</p>
<p>关闭csrf</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http.csrf().disable()</span><br></pre></td></tr></table></figure>

<h2 id="微服务"><a href="#微服务" class="headerlink" title="微服务"></a>微服务</h2><h3 id="数据库"><a href="#数据库" class="headerlink" title="数据库"></a>数据库</h3><p><img src="" data-original="https://s1.ax1x.com/2023/07/26/pCjwOSS.png" alt="image-20230726154749582"></p>
<h3 id="搭建项目"><a href="#搭建项目" class="headerlink" title="搭建项目"></a>搭建项目</h3><p><img src="" data-original="https://s1.ax1x.com/2023/07/26/pCjax1g.png" alt="image-20230726154749582"></p>
<h3 id="前置知识"><a href="#前置知识" class="headerlink" title="前置知识"></a>前置知识</h3><h4 id="Nacos"><a href="#Nacos" class="headerlink" title="Nacos"></a>Nacos</h4><p>阿里巴巴的注册中心，网关服务（9001端口）通过注册中心转发到权限管理服务（8081端口）</p>
<p>启动：Windows点击<code>startup.cmd</code>，Linux运行<code>startup.sh</code></p>
<p>访问地址：<a target="_blank" rel="noopener" href="http://localhost:8848/nacos%EF%BC%8C%E9%BB%98%E8%AE%A4%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81%E9%83%BD%E6%98%AFnacos">http://localhost:8848/nacos，默认用户名和密码都是nacos</a></p>
<h2 id="认证流程"><a href="#认证流程" class="headerlink" title="认证流程"></a>认证流程</h2><p><a target="_blank" rel="noopener" href="https://imgse.com/i/pCvJddf"><img src="" data-original="https://s1.ax1x.com/2023/07/27/pCvJddf.png" alt="pCvJddf.png"></a></p>
<p><code>UsernamePasswordAuthenticationFilter</code></p>
<p>继承<code>AbstractAuthenticationProcessingFilter</code>父类</p>
<p>查看父类的<code>doFilter</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest req, ServletResponse res, FilterChain chain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">     <span class="type">HttpServletRequest</span> <span class="variable">request</span> <span class="operator">=</span> (HttpServletRequest)req;</span><br><span class="line">     <span class="type">HttpServletResponse</span> <span class="variable">response</span> <span class="operator">=</span> (HttpServletResponse)res;</span><br><span class="line">     <span class="comment">// 判断是否是post提交</span></span><br><span class="line">     <span class="keyword">if</span> (!<span class="built_in">this</span>.requiresAuthentication(request, response)) &#123;</span><br><span class="line">         chain.doFilter(request, response);</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="keyword">if</span> (<span class="built_in">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">             <span class="built_in">this</span>.logger.debug(<span class="string">&quot;Request is to process authentication&quot;</span>);</span><br><span class="line">         &#125;</span><br><span class="line"><span class="comment">// 进行身份认证，认证成功将信息封装到Authentication中</span></span><br><span class="line">         Authentication authResult;</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">             authResult = <span class="built_in">this</span>.attemptAuthentication(request, response);</span><br><span class="line">             <span class="keyword">if</span> (authResult == <span class="literal">null</span>) &#123;</span><br><span class="line">                 <span class="keyword">return</span>;</span><br><span class="line">             &#125;	</span><br><span class="line">	<span class="comment">// session策略处理</span></span><br><span class="line">             <span class="built_in">this</span>.sessionStrategy.onAuthentication(authResult, request, response);</span><br><span class="line">         &#125; <span class="keyword">catch</span> (InternalAuthenticationServiceException var8) &#123;</span><br><span class="line">             <span class="comment">// 认证失败</span></span><br><span class="line">             <span class="built_in">this</span>.logger.error(<span class="string">&quot;An internal error occurred while trying to authenticate the user.&quot;</span>, var8);</span><br><span class="line">             <span class="built_in">this</span>.unsuccessfulAuthentication(request, response, var8);</span><br><span class="line">             <span class="keyword">return</span>;</span><br><span class="line">         &#125; <span class="keyword">catch</span> (AuthenticationException var9) &#123;</span><br><span class="line">             <span class="built_in">this</span>.unsuccessfulAuthentication(request, response, var9);</span><br><span class="line">             <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"><span class="comment">// 认证成功</span></span><br><span class="line">         <span class="comment">// continueChainBeforeSuccessfulAuthentication默认为false</span></span><br><span class="line">         <span class="keyword">if</span> (<span class="built_in">this</span>.continueChainBeforeSuccessfulAuthentication) &#123;</span><br><span class="line">             chain.doFilter(request, response);</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="built_in">this</span>.successfulAuthentication(request, response, chain, authResult);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>查看<code>UsernamePasswordAuthenticationFilter</code>子类中的<code>attemptAuthentication</code>方法（上述代码中的<code>attemptAuthentication</code>方法）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">public</span> Authentication <span class="title function_">attemptAuthentication</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> AuthenticationException &#123;</span><br><span class="line">     <span class="comment">// 判断是否是post请求</span></span><br><span class="line">     <span class="keyword">if</span> (<span class="built_in">this</span>.postOnly &amp;&amp; !request.getMethod().equals(<span class="string">&quot;POST&quot;</span>)) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">AuthenticationServiceException</span>(<span class="string">&quot;Authentication method not supported: &quot;</span> + request.getMethod());</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// 检查参数书否为空</span></span><br><span class="line">         <span class="type">String</span> <span class="variable">username</span> <span class="operator">=</span> <span class="built_in">this</span>.obtainUsername(request);</span><br><span class="line">         <span class="type">String</span> <span class="variable">password</span> <span class="operator">=</span> <span class="built_in">this</span>.obtainPassword(request);</span><br><span class="line">         <span class="keyword">if</span> (username == <span class="literal">null</span>) &#123;</span><br><span class="line">             username = <span class="string">&quot;&quot;</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (password == <span class="literal">null</span>) &#123;</span><br><span class="line">             password = <span class="string">&quot;&quot;</span>;</span><br><span class="line">         &#125;</span><br><span class="line"><span class="comment">// 去掉空格</span></span><br><span class="line">         username = username.trim();</span><br><span class="line">         <span class="comment">// 使用获取数据构造对象，标记未认证</span></span><br><span class="line">         <span class="type">UsernamePasswordAuthenticationToken</span> <span class="variable">authRequest</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">UsernamePasswordAuthenticationToken</span>(username, password);</span><br><span class="line">         <span class="comment">// 将请求的信息设置到Authentication对象中</span></span><br><span class="line">         <span class="built_in">this</span>.setDetails(request, authRequest);</span><br><span class="line">         <span class="comment">// 进行身份验证（调用userDetailsService）</span></span><br><span class="line">         <span class="keyword">return</span> <span class="built_in">this</span>.getAuthenticationManager().authenticate(authRequest);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>查看<code>ProviderManager</code>实现<code>AuthenticationManager</code>接口（该接口包含上述代码最后一行的的<code>authenticate</code>方法）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">public</span> Authentication <span class="title function_">authenticate</span><span class="params">(Authentication authentication)</span> <span class="keyword">throws</span> AuthenticationException &#123;</span><br><span class="line">     <span class="comment">// 获取Authentication的类型，即UsernamePasswordAuthenticationToken.class</span></span><br><span class="line">     Class&lt;? <span class="keyword">extends</span> <span class="title class_">Authentication</span>&gt; toTest = authentication.getClass();</span><br><span class="line">     <span class="type">AuthenticationException</span> <span class="variable">lastException</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">     <span class="type">AuthenticationException</span> <span class="variable">parentException</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">     <span class="type">Authentication</span> <span class="variable">result</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">     <span class="type">Authentication</span> <span class="variable">parentResult</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">     <span class="type">boolean</span> <span class="variable">debug</span> <span class="operator">=</span> logger.isDebugEnabled();</span><br><span class="line">     <span class="comment">// 获取认证方式列表List&lt;AuthenticationProvider&gt;迭代器</span></span><br><span class="line">     <span class="type">Iterator</span> <span class="variable">var8</span> <span class="operator">=</span> <span class="built_in">this</span>.getProviders().iterator();</span><br><span class="line"></span><br><span class="line">     <span class="keyword">while</span>(var8.hasNext()) &#123;</span><br><span class="line">         <span class="type">AuthenticationProvider</span> <span class="variable">provider</span> <span class="operator">=</span> (AuthenticationProvider)var8.next();</span><br><span class="line">         <span class="comment">// 判断当前AuthenticationProvider是否适用UsernamePasswordAuthenticationToken.class类型的Authentication</span></span><br><span class="line">         <span class="keyword">if</span> (provider.supports(toTest)) &#123;</span><br><span class="line">             <span class="keyword">if</span> (debug) &#123;</span><br><span class="line">                 logger.debug(<span class="string">&quot;Authentication attempt using &quot;</span> + provider.getClass().getName());</span><br><span class="line">             &#125;</span><br><span class="line"></span><br><span class="line">             <span class="keyword">try</span> &#123;</span><br><span class="line">                 <span class="comment">// 认证成功会返回标记已认证的Authentication对象</span></span><br><span class="line">                 result = provider.authenticate(authentication);</span><br><span class="line">                 <span class="keyword">if</span> (result != <span class="literal">null</span>) &#123;</span><br><span class="line">                     <span class="comment">// 信息拷贝到result中</span></span><br><span class="line">                     <span class="built_in">this</span>.copyDetails(authentication, result);</span><br><span class="line">                     <span class="keyword">break</span>;</span><br><span class="line">                 &#125;</span><br><span class="line">             &#125; <span class="keyword">catch</span> (InternalAuthenticationServiceException | AccountStatusException var13) &#123;</span><br><span class="line">                 <span class="built_in">this</span>.prepareException(var13, authentication);</span><br><span class="line">                 <span class="keyword">throw</span> var13;</span><br><span class="line">             &#125; <span class="keyword">catch</span> (AuthenticationException var14) &#123;</span><br><span class="line">                 lastException = var14;</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">if</span> (result == <span class="literal">null</span> &amp;&amp; <span class="built_in">this</span>.parent != <span class="literal">null</span>) &#123;</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">             <span class="comment">// 认证失败，使其父类型AuthenticationManager进行验证</span></span><br><span class="line">             result = parentResult = <span class="built_in">this</span>.parent.authenticate(authentication);</span><br><span class="line">         &#125; <span class="keyword">catch</span> (ProviderNotFoundException var11) &#123;</span><br><span class="line">         &#125; <span class="keyword">catch</span> (AuthenticationException var12) &#123;</span><br><span class="line">             parentException = var12;</span><br><span class="line">             lastException = var12;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">if</span> (result != <span class="literal">null</span>) &#123;</span><br><span class="line">         <span class="comment">// 认证成功，去掉result铭感信息</span></span><br><span class="line">         <span class="keyword">if</span> (<span class="built_in">this</span>.eraseCredentialsAfterAuthentication &amp;&amp; result <span class="keyword">instanceof</span> CredentialsContainer) &#123;</span><br><span class="line">             <span class="comment">// 去除的过程就是调用CredentialsContainer的eraseCredentials方法</span></span><br><span class="line">             ((CredentialsContainer)result).eraseCredentials();</span><br><span class="line">         &#125;</span><br><span class="line"><span class="comment">// 发布成功认证的事件</span></span><br><span class="line">         <span class="keyword">if</span> (parentResult == <span class="literal">null</span>) &#123;</span><br><span class="line">             <span class="built_in">this</span>.eventPublisher.publishAuthenticationSuccess(result);</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">return</span> result;</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// 认证失败抛出异常</span></span><br><span class="line">         <span class="keyword">if</span> (lastException == <span class="literal">null</span>) &#123;</span><br><span class="line">             lastException = <span class="keyword">new</span> <span class="title class_">ProviderNotFoundException</span>(<span class="built_in">this</span>.messages.getMessage(<span class="string">&quot;ProviderManager.providerNotFound&quot;</span>, <span class="keyword">new</span> <span class="title class_">Object</span>[]&#123;toTest.getName()&#125;, <span class="string">&quot;No AuthenticationProvider found for &#123;0&#125;&quot;</span>));</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (parentException == <span class="literal">null</span>) &#123;</span><br><span class="line">             <span class="built_in">this</span>.prepareException((AuthenticationException)lastException, authentication);</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">throw</span> lastException;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<p>上述代码的去掉敏感信息方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">class</span> <span class="title class_">AbstractAuthenticationToken</span> <span class="keyword">implements</span> <span class="title class_">Authentication</span>, CredentialsContainer &#123;</span><br><span class="line">    <span class="comment">// 实现CredentialsContainer接口</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">eraseCredentials</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// 前端传入的密码设为null</span></span><br><span class="line">        <span class="built_in">this</span>.eraseSecret(<span class="built_in">this</span>.getCredentials());</span><br><span class="line">        <span class="built_in">this</span>.eraseSecret(<span class="built_in">this</span>.getPrincipal());</span><br><span class="line">        <span class="built_in">this</span>.eraseSecret(<span class="built_in">this</span>.details);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>认证成功<code>successfulAuthentication</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">  <span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">successfulAuthentication</span><span class="params">(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">      <span class="keyword">if</span> (<span class="built_in">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">          <span class="built_in">this</span>.logger.debug(<span class="string">&quot;Authentication success. Updating SecurityContextHolder to contain: &quot;</span> + authResult);</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">// 将认证成功的用户信息Authentication封装到SecurtyContext对象，并存入SecurityContextHolader</span></span><br><span class="line">      SecurityContextHolder.getContext().setAuthentication(authResult);</span><br><span class="line">      <span class="comment">// 处理RememberMe</span></span><br><span class="line">      <span class="built_in">this</span>.rememberMeServices.loginSuccess(request, response, authResult);</span><br><span class="line">      <span class="keyword">if</span> (<span class="built_in">this</span>.eventPublisher != <span class="literal">null</span>) &#123;</span><br><span class="line">          <span class="comment">// 发布认证成功的属性	</span></span><br><span class="line">          <span class="built_in">this</span>.eventPublisher.publishEvent(<span class="keyword">new</span> <span class="title class_">InteractiveAuthenticationSuccessEvent</span>(authResult, <span class="built_in">this</span>.getClass()));</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">// 调用成功认证处理器</span></span><br><span class="line">      <span class="built_in">this</span>.successHandler.onAuthenticationSuccess(request, response, authResult);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p>认证失败<code>unsuccessfulAuthentication</code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title function_">unsuccessfulAuthentication</span><span class="params">(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">    <span class="comment">//清楚线程在SecurityContextHolder中的SecurtyContext对象</span></span><br><span class="line">    SecurityContextHolder.clearContext();</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">        <span class="built_in">this</span>.logger.debug(<span class="string">&quot;Authentication request failed: &quot;</span> + failed.toString(), failed);</span><br><span class="line">        <span class="built_in">this</span>.logger.debug(<span class="string">&quot;Updated SecurityContextHolder to contain null Authentication&quot;</span>);</span><br><span class="line">        <span class="built_in">this</span>.logger.debug(<span class="string">&quot;Delegating to authentication failure handler &quot;</span> + <span class="built_in">this</span>.failureHandler);</span><br><span class="line">    &#125;</span><br><span class="line">	 <span class="comment">// 处理RememberMe</span></span><br><span class="line">    <span class="built_in">this</span>.rememberMeServices.loginFail(request, response);</span><br><span class="line">    <span class="comment">// 调用认证失败处理器</span></span><br><span class="line">    <span class="built_in">this</span>.failureHandler.onAuthenticationFailure(request, response, failed);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://imgse.com/i/pCvJGzd"><img src="" data-original="https://s1.ax1x.com/2023/07/27/pCvJGzd.png" alt="pCvJGzd.png"></a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://www.lijunxi.site">Jixer</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://www.lijunxi.site/posts/1714087543/">http://www.lijunxi.site/posts/1714087543/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://www.lijunxi.site" target="_blank">Jixer的小屋</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/SpringSecurity/">SpringSecurity</a></div><div class="post_share"><div class="social-share" data-image="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="/pluginsSrc/butterfly-extsrc/sharejs/dist/css/share.min.css?v=1.1.3" media="print" onload="this.media='all'"><script src="/pluginsSrc/butterfly-extsrc/sharejs/dist/js/social-share.min.js?v=1.1.3" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/1476420007/" title="SpringCloud学习笔记"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">SpringCloud学习笔记</div></div></a></div><div class="next-post pull-right"><a href="/posts/3993141914/" title="SpringSecurity动态权限控制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SpringSecurity动态权限控制</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/3993141914/" title="SpringSecurity动态权限控制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-16</div><div class="title">SpringSecurity动态权限控制</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="" data-original="https://q1.qlogo.cn/g?b=qq&amp;nk=2770063826&amp;s=640" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Jixer</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">19</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/2770063826"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E6%9C%AC%E5%8E%9F%E7%90%86"><span class="toc-text">基本原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%87%E6%BB%A4%E5%99%A8%E5%8A%A0%E8%BD%BD%E6%B5%81%E7%A8%8B"><span class="toc-text">过滤器加载流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DelegatingFilterProxy%E7%B1%BB"><span class="toc-text">DelegatingFilterProxy类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#FilterChainProxy%E7%B1%BB"><span class="toc-text">FilterChainProxy类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%87%8D%E8%A6%81%E6%8E%A5%E5%8F%A3"><span class="toc-text">重要接口</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#UserDetailsService"><span class="toc-text">UserDetailsService</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#PasswordEncoder"><span class="toc-text">PasswordEncoder</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#SpringSecurity-Web-%E6%9D%83%E9%99%90%E6%96%B9%E6%A1%88"><span class="toc-text">SpringSecurity Web 权限方案</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%BE%E7%BD%AE%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E5%AF%86%E7%A0%81"><span class="toc-text">设置用户名和密码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B4%E5%90%88%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AE%9E%E7%8E%B0%E7%99%BB%E5%BD%95"><span class="toc-text">整合数据库实现登录</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%AF%E5%BE%84%E6%8B%A6%E6%88%AA%E8%B7%AF%E5%BE%84%E6%8B%A6%E6%88%AA"><span class="toc-text">路径拦截路径拦截</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%92%E8%89%B2%E6%9D%83%E9%99%90%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6"><span class="toc-text">角色权限访问控制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#hasAuthority"><span class="toc-text">hasAuthority</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#hasAnyAuthority"><span class="toc-text">hasAnyAuthority</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#hasRole"><span class="toc-text">hasRole</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#hasAnyRole"><span class="toc-text">hasAnyRole</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89403%E9%A1%B5%E9%9D%A2"><span class="toc-text">自定义403页面</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3%E4%BD%BF%E7%94%A8"><span class="toc-text">注解使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Secured"><span class="toc-text">@Secured</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PreAuthorize"><span class="toc-text">@PreAuthorize</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PostAuthorize"><span class="toc-text">@PostAuthorize</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PostFilter"><span class="toc-text">@PostFilter</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PreFilter"><span class="toc-text">@PreFilter</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%80%80%E5%87%BA%E7%99%BB%E5%BD%95"><span class="toc-text">退出登录</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CSRF"><span class="toc-text">CSRF</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BE%AE%E6%9C%8D%E5%8A%A1"><span class="toc-text">微服务</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-text">数据库</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%90%AD%E5%BB%BA%E9%A1%B9%E7%9B%AE"><span class="toc-text">搭建项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86"><span class="toc-text">前置知识</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Nacos"><span class="toc-text">Nacos</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%A4%E8%AF%81%E6%B5%81%E7%A8%8B"><span class="toc-text">认证流程</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/2029624507/" title="2022年算法队选拔赛">2022年算法队选拔赛</a><time datetime="2024-05-09T15:00:27.000Z" title="发表于 2024-05-09 23:00:27">2024-05-09</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/1978524057/" title="牛客小白月赛84">牛客小白月赛84</a><time datetime="2024-05-08T14:40:35.000Z" title="发表于 2024-05-08 22:40:35">2024-05-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/131339317/" title="软件测试资料">软件测试资料</a><time datetime="2024-05-07T03:12:52.000Z" title="发表于 2024-05-07 11:12:52">2024-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/2394234105/" title="第十四届蓝桥杯B组国赛">第十四届蓝桥杯B组国赛</a><time datetime="2024-05-05T13:40:15.000Z" title="发表于 2024-05-05 21:40:15">2024-05-05</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/1405472621/" title="Leetcode第396场周赛">Leetcode第396场周赛</a><time datetime="2024-05-05T03:58:25.000Z" title="发表于 2024-05-05 11:58:25">2024-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2024 By Jixer</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://beian.miit.gov.cn/#/Integrated/index" style="color:white" target="_blank">蜀ICP备2022009955号-1</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js?v=4.13.0"></script><script src="/js/main.js?v=4.13.0"></script><script src="/pluginsSrc/@fancyapps/ui/dist/fancybox/fancybox.umd.js?v=5.0.33"></script><div class="js-pjax"></div><script src="/js/custom-fancybox-umd-min.js"></script><script src="/js/custom-busuanzi-pure-mini.js"></script><script src="/js/Valine.min.js"></script><script src="/js/custom-social-share.min.js"></script><script src="/js/custom-typed-umd-min.js"></script><script src="/js/av-min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js?v=4.13.0"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>